import BaseService from '@/utils/base/service';
import makeRequest from '@/utils/request/request';
import { LoginModel } from '../model';
import LoginManager from '../manager';

export default class LoginService extends BaseService {
	constructor() {
		super('/unapp/pagehome');  // 设置基础路径
	}

	/**
	 * 微信登录
	 */
	async loginWithCode(mobile : string, authCode : string) : Promise<LoginModel> {
		let shareUserId = LoginManager.getInstance().shareUserId;
		const response = await makeRequest({
			url: `${this.endpoint}/phoneSmsLogin`,
			method: 'POST',
			data: { mobile, authCode, shareUserId },
		});
		const data = new LoginModel(response.data)
		data.saveCache()
		return data;
	}

	/**
	 * 获取openId
	 */
	async getOpenId() : Promise<string> {
		try {
			const js_code : any = await new Promise((resolve, reject) => {
				uni.login({
					provider: 'weixin',
					onlyAuthorize: true,
					success: resolve,
					fail: reject
				});
			});
			console.log('获取到了WX Code:', js_code);
			const response = await makeRequest({
				url: `${this.endpoint}/wxapp/getOpenId`,
				method: 'POST',
				data: { code: js_code.code },
				hideLoading: true
			});
			return response.data;
		} catch (error) {
			console.error('获取用户信息失败:', error);
			throw new Error('用户信息获取失败，请重试');
		}
	}

	/**
	 * 获取验证码
	 */
	async getVerificationCode(mobile : string) : Promise<any> {
		let type = '2';
		const response = await makeRequest({
			url: `${this.endpoint}/getSmsAuthCode`,
			method: 'GET',
			data: { mobile, type },
		});
		return response.data;
	}

	/**
	 * 验证码登录
	 */
	async requestPhoneNumber(code : string, encryptedData : string, iv : string) : Promise<LoginModel> {
		let shareUserId = LoginManager.getInstance().shareUserId;
		const response = await makeRequest({
			url: `${this.endpoint}/wxapp/auth`,
			method: 'POST',
			data: { code, encryptedData, iv, shareUserId },
		});
		const data = new LoginModel(response.data)
		data.saveCache()
		return data;
	}

	/**
	 * 密码登录
	 */
	async loginWithPassword(mobile : string, pwd : string) : Promise<LoginModel> {
		const response = await makeRequest({
			url: `${this.endpoint}/phonePwdLogin`,
			method: 'POST',
			data: { mobile, pwd },
		});
		const data = new LoginModel(response.data)
		data.saveCache()
		return data;
	}

	/**
	 * 忘记密码
	 */
	async forgotPassword(mobile : string, code : string, pwd : string) : Promise<LoginModel> {
		const response = await makeRequest({
			url: `${this.endpoint}/findPwd`,
			method: 'POST',
			data: { mobile, code, pwd },
		});
		const data = new LoginModel(response.data)
		data.saveCache()
		return data;
	}

	/**
	 * 退出登录
	 */
	async logout() : Promise<void> {
		try {
			await makeRequest({
				url: `${this.endpoint}/logout`,
				method: 'POST',
			});
			console.log('用户已成功退出登录');
		} catch (error) {
			console.error('退出登录失败:', error);
			throw new Error('退出登录失败，请重试');
		}
	}
}